package jh.com.jhappbf.contract;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.dispatchcar.ContractSelectSetting;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.ContractModel;
import jh.com.jhappbf.model.ContractSettingModel;
import jh.com.jhappbf.model.PlanModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

public class ContractQuery extends AbActivity {
    private View mContentView;
    private View mErrorView;
    private Context mAppContext;
    private LinearLayout mHeaderLayout;
    private ListView mListView;
    private Button mTryAgain;
    private List<JSONObject> mData;
    private Button mTitleRightBtn;
    private List<String> mHeaderTitle;
    private Drawable mLeftDrawable;
    private int mColumnWidth;
    private AbLoadDialogFragment mDialogFragment = null;
    private myBaseAdapter mAdapter;
    private ContractSettingModel mSettingModel;
    private final int GETSETTING = 0X0001;
    private String mFlag;
    private EditText select_edit;
    private Button query_btn;

//    private String contractCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.contract_select_activity, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        Intent i = getIntent();
        mFlag = i.getStringExtra("flag");

//        contractCode = i.getStringExtra("contractCode");
        mSettingModel = i.getParcelableExtra("setting");

        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("项目选择");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAbTitleBar.setLogoOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.putExtra("result", mSettingModel);
                setResult(RESULT_OK, i);
                ContractQuery.this.finish();
            }
        });
        View rightViewMore = mInflater.inflate(R.layout.title_right_app_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_btn);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mAppContext = getApplicationContext();
        mHeaderLayout = mContentView.findViewById(R.id.contract_select_title);
        mListView = mContentView.findViewById(R.id.contract_select_listView);
        select_edit=mContentView.findViewById(R.id.select_edit);
        query_btn=mContentView.findViewById(R.id.query_btn);
        query_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
            }
        });
        mAdapter = new myBaseAdapter();
        mData = new ArrayList<>();
        mListView.setAdapter(mAdapter);
        mTryAgain = mErrorView.findViewById(R.id.network_error_btn);
        mHeaderTitle = new ArrayList<>();
        mLeftDrawable = ContextCompat.getDrawable(this, R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(),
                mLeftDrawable.getMinimumHeight());
        mColumnWidth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 55, getResources().getDisplayMetrics());
        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mContentView);
            refresh();
        });

        mTitleRightBtn.setOnClickListener(v -> {
            Intent i = new Intent(ContractQuery.this, ContractSelectSetting.class);
            i.putExtra("flag", "input");
            i.putExtra("setting", mSettingModel);
            startActivityForResult(i, GETSETTING);
        });
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            JSONObject object = mData.get(position);

        });
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            PopupMenu menu = new PopupMenu(ContractQuery.this, view);
            getMenuInflater().inflate(R.menu.contract_manager_menu,
                        menu.getMenu());
            menu.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
//                    case R.id.contract_append_menu_item:
//                        appendContract(position);
//                        break;
                    case R.id.contract_detail_menu_item:
                        openDetail(position);
                        break;
//                    case R.id.contract_delete_menu_item:
//                        stopContract(position);
//                        break;
                    case R.id.contract_append_menu_item:
                        updatePlan(position);
                        break;
//                    case R.id.contract_start_menu_item:
//                        startContract(position);
//                        break;
                    default:
                        break;
                }
                return true;
            });
            menu.show();
            return true;
        });
        refresh();
    }
    /**
     * 打开计划
     *
     * @param position
     */
    private void openDetail(int position) {
        JSONObject object = mData.get(position);
        Intent i = new Intent(ContractQuery.this, CollectWeigh.class);
        i.putExtra("planId", object.optString("计划单号"));
        startActivity(i);
    }

    /**
     * 修改计划
     *
     * @param position
     */
    private void updatePlan(int position) {
        JSONObject object = mData.get(position);
        ContractModel model = new ContractModel();
        Intent i = new Intent(ContractQuery.this, ContractAdd.class);
        model.setPlanId(object.optString("计划单号"));
        model.setAccount(object.optString("开户人"));
        model.setPhone(object.optString("联系电话"));
        model.setUnit(object.optString("单位"));
        model.setCargoname(object.optString("货名"));
        model.setSepc(object.optString("规格"));
        model.setSender(object.optString("发货"));
        model.setReceiver(object.optString("收货"));
        model.setAmount(object.optString("计划量"));
        model.setCredit(object.optString("信用额度"));
        model.setTypes(object.optString("类型"));
        model.setMoney(object.optString("金额"));
        model.setPrice(object.optString("单价"));
        model.setMemo(object.optString("备注"));
        model.setSalePerson(object.optString("销售人员"));
        model.setAddPerson(object.optString("计划人"));
        i.putExtra("data", model);
        i.putExtra("flag", "update");
        startActivityForResult(i, 10068);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == GETSETTING) {
            mSettingModel = data.getParcelableExtra("result");
            if (mSettingModel != null) {
                refresh();
            }
        }else if (requestCode == 10068) {
            refresh();
        }
    }

    // /刷新
    private void refresh() {
        mDialogFragment = AbDialogUtil.showLoadDialog(ContractQuery.this,
                R.mipmap.ic_load, "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> getData(mSettingModel));
    }

    // /获取数据
    private void getData(ContractSettingModel model) {
        String methodName = "getAllPlan";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("startTime");
        param.add("endTime");
        param.add("spec");
        param.add("cargoname");
        param.add("sender");
        param.add("receiver");
        param.add("like");


        if (model == null) {
            Date date = new Date();
            String end = "";
            String start = "";
            value.add(start);
            value.add(end);
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add(select_edit.getText().toString());


        } else {
            value.add(model.getStartTime()+":00");
            value.add(model.getEndTime()+":00");
            value.add(model.getSpec());
            value.add(model.getCargoname());
            value.add(model.getSender());
            value.add(model.getReceiver());
            value.add(select_edit.getText().toString());

        }

        Listener<String> listener = response -> {

            AbDialogUtil.removeDialog(ContractQuery.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }

            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null) {
                mHeaderTitle = new ArrayList<>();
                if (newListData.size() > 0) {
                    String[] head = newListData.get(0).optString("alias").split(",");
                    mHeaderTitle = Arrays.asList(head);
//                    makeHead();
                }
                mData.clear();
                mData.addAll(newListData);
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractQuery.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            setAbContentView(mErrorView);
            mData.clear();
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    class myBaseAdapter extends BaseAdapter
    {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if(convertView == null)
            {
                holder = new ViewHolder();
                LayoutInflater inflater =  (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.contract_query_list_item, null);
                holder.plateNumber = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_platenum);
                holder.cargoname  = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_cargoname);
                holder.states= (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_state);
                holder.stime = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_times);
                holder.guige = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_guige);
                holder.price = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_price);
                holder.leiji = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_leiji);
                holder.type = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_type);
                holder.shengyu = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_shengyu);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject object= mData.get(position);

            holder.plateNumber.setText("计划单号: "+object.optString("计划单号"));
            holder.stime.setText("收货: "+object.optString("收货"));
            holder.type.setText("类型: "+object.optString("类型"));
            holder.cargoname.setText("货名: "+object.optString("货名"));
            holder.guige.setText("规格: "+object.optString("规格"));
            holder.price.setText("联系电话: "+object.optString("联系电话"));
            holder.leiji.setText("信用额度: "+	new DecimalFormat("0.00").format(Double.parseDouble(object.optString("信用额度"))));
            holder.shengyu.setText("剩余量: "+new BigDecimal(object.optString("剩余量")).toString());
            return convertView;
        }
    }

    class ViewHolder
    {
        public String id ;
        public ImageView img;
        public TextView plateNumber;
        public TextView cargoname;
        public TextView states;
        public TextView stime;
        public TextView guige;
        public TextView price;
        public TextView leiji;
        public TextView type;
        public TextView shengyu;

    }
}

